layui.use(['table', 'admin', 'ax'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;

    /**
     * 出库订单表管理 Outbound Order Management
     */
    var OutOrder = {
        tableId: "outOrderTable"
    };

    /**
     * 出库订单明细表管理 Outbound Order Details Management
     */
    var OutOrderDetailed = {
        tableId: "outOrderDetailedTable"
    };

    /**
     * 初始化表格的列 Initialize Table Columns
     */
    OutOrder.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'id', hide: true, title: 'Primary Key ID'},
            {field: 'customerNumber', title: 'Customer Order No.', style:'color: #2b85e4;font-weight: 600;',width:150},
            {field: 'outOrderStatus', title: 'Order Status', templet: '#outOrderStatusTpl', event: 'outOrderStatusSign'},
            {field: 'setMentiontime', title: 'Shipment Date', style:'font-weight: 600;'},
            {field: 'createUserName', title: 'Created By'},
            {field: 'getUnit', title: 'Unloading Unit', style:'font-weight: 600;',width:180},
            {field: 'getLocation', title: 'Unloading Location',width:250},
            {field: 'outWay', title: 'Outbound Method'},
            {field: 'note', title: 'Remarks'},
            {field: 'getUnitId', title: 'Unloading Unit ID'},
            {field: 'kilometer', title: 'Kilometers'},
            {field: 'storehouseName', title: 'Warehouse Name'},
            {field: 'outCustomerName', title: 'Customer Name'},
            {field: 'outOrderNumber', title: 'Outbound Order No.'},
            {field: 'setUnit', title: 'Loading Unit'},
            {field: 'setLocation', title: 'Loading Address'},
            {field: 'createTime', title: 'Creation Time'},
            {field: 'submitTime', title: 'Submission Time'},
            {field: 'submitterName', title: 'Submitted By'},
            {fixed: 'right',width: 90,align: 'center', toolbar: '#tableBar', title: 'Operations'}
        ]];
    };

    /**
     * 点击查询按钮 Click Search Button
     */
    OutOrder.search = function () {
        var queryData = {};
        queryData['condition'] = $("#condition").val();
        queryData['outCustomerId'] = $("#outCustomerId").val();
        queryData['outStorehouseId'] = $("#outStorehouseId").val();
        table.reload(OutOrder.tableId, {
            where: queryData, page: {curr: 1},
             done:function () {
            }
        });
    };
    OutOrder.toJSTOutOrder = function () {
        // var ajax = new $ax(Feng.ctxPath + "/outOrder/getJSTOutOrder" );
        // var result = ajax.start();
        // console.log(result)
        // Feng.success("拉取成功!");
        window.location.href = Feng.ctxPath + '/outOrder/toJSTOutOrder';
    };

    // 导入excel按钮点击事件 Import Excel Button Click Event
    OutOrder.importExcel = function () {
        layer.open({
            type: 2,
            title: 'Outbound Order Import',
            area: ['1000px', '550px'],
            anim: 5,
            content: Feng.ctxPath + '/outOrder/toimportExcel',
            end: function () {
                table.reload(OutOrder.tableId);
                outOrder(null);
                OutOrder.search();
            }
        });
    };

    // 导入excel按钮点击事件 Import Excel Button Click Event
    OutOrder.importExcelDD = function () {
        layer.open({
            type: 2,
            title: 'Outbound Order Import - Duodian',
            area: ['1000px', '550px'],
            anim: 5,
            content: Feng.ctxPath + '/outOrder/toimportExcelDD',
            end: function () {
                table.reload(OutOrder.tableId);
                outOrder(null);
                OutOrder.search();
            }
        });
    };

    // 导入excel按钮点击事件 Import Excel Button Click Event
    OutOrder.importExcel_ha = function () {
        layer.open({
            type: 2,
            title: 'Outbound Order Import - Haian',
            area: ['1000px', '550px'],
            anim: 5,
            content: Feng.ctxPath + '/outOrder/toimportExcel_ha',
            end: function () {
                table.reload(OutOrder.tableId);
                outOrder(null);
                OutOrder.search();
            }
        });
    };

    /**
     * 弹出添加对话框 Open Add Dialog
     */
    OutOrder.openAddDlg = function () {
        window.location.href = Feng.ctxPath + '/outOrder/add';
    };

    /**
     * 弹出添加对话框
     */
    OutOrder.openAddDlg = function () {
        window.location.href = Feng.ctxPath + '/outOrder/add';
    };

    /**
     * 导出excel按钮 Export Excel Button
     */
    OutOrder.exportExcel = function () {
        var checkRows = table.checkStatus(OutOrder.tableId);
        if (checkRows.data.length === 0) {
            Feng.error("Please select data to export");
        } else {
            table.exportFile(tableResult.config.id, checkRows.data, 'xls');
        }
    };

    /**
     * 点击编辑 Click Edit
     *
     * @param data 点击按钮时候的行数据 Row data when button is clicked
     */
    OutOrder.openEditDlg = function (data) {
        window.location.href = Feng.ctxPath + '/outOrder/edit?id=' + data.id;
    };

    /**
     * 点击删除 Click Delete
     *
     * @param data 点击按钮时候的行数据 Row data when button is clicked
     */
    OutOrder.onDeleteItem = function (data) {
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/outOrder/delete", function (data) {
                Feng.success("Deletion successful!");
                table.reload(OutOrder.tableId);
            }, function (data) {
                Feng.error("Deletion failed!" + data.responseJSON.message + "!");
            });
            ajax.set("id", data.id);
            ajax.start();
        };
        Feng.confirm("Confirm deletion?", operation);
    };

    // 渲染表格 Render table
    var tableResult = table.render({
        elem: '#' + OutOrder.tableId,
        url: Feng.ctxPath + '/outOrder/list',
        page: true,
        limit: 30,
        height: 410,
        toolbar: '#demotoolbarfrom',
        cellMinWidth: 100,
        cols: OutOrder.initColumn()
    });

    // 批量提交 Batch Submit
    OutOrder.submit = function () {
        var checkStatus = table.checkStatus('outOrderTable');
        data = checkStatus.data;
        if (data.length>0) {
            var ids = [];
            for (var i = 0; i < data.length; i++) {
                ids.push(data[i].id);
            }
            layer.confirm('Confirm selected orders for submission?', function(index){
            	layer.close(index);
            	var msg;
                $.ajax({
                	url:Feng.ctxPath + "/outOrder/submits?ids="+ids,
                	cache: false,
                	dataType:"json",
                	beforeSend:function(){
                    	//弹出加载中
                		msg = layer.msg('Submitting... Please wait patiently', {
	              			  icon: 16,
	              			  shade: [0.2,'#000'], //0.1透明度的白色背景
	              			  time: false
                		});
                	},
                	success:function(data){
						console.log(data)
                    	layer.close(msg); 
                		if (data.success) {
                        	Feng.success("Submission successful!");
                			table.reload(OutOrder.tableId);
						} else {
							if (data.message !=null &&data.message!='') {
			    				var msg2 =  layer.open({
				  					  title: 'Notification' ,
				  					  content: data.message,
				  					  btn: ['Confirm'],
				  					  yes: function (){
				  						  	layer.close(msg2);
                							table.reload(OutOrder.tableId);
				  					  }
			    				});     
							} else {
	  		                    Feng.error("Submission failed!");
                				table.reload(OutOrder.tableId);
							}
						}
                	},
                	error:function(data){
                    	layer.close(msg); 
                        Feng.error("Submission failed!" + data.responseJSON.message)
            			table.reload(OutOrder.tableId);
                	}
                })
            }); 
        } else {
            layer.alert('Please select at least one record');
        }
    };


    // 批量提交
    OutOrder.submitHshn = function () {
        var checkStatus = table.checkStatus('outOrderTable');
        data = checkStatus.data;
        if (data.length>0) {
            var ids = [];
            for (var i = 0; i < data.length; i++) {
                ids.push(data[i].id);
            }
            layer.confirm('Confirm selected orders for submission?', function(index){
                layer.close(index);
                var msg;
                $.ajax({
                    url:Feng.ctxPath + "/outOrder/submitsHshn?ids="+ids,
                    cache: false,
                    dataType:"json",
                    beforeSend:function(){
                        //弹出加载中
                        msg = layer.msg('Submitting... Please wait patiently', {
                            icon: 16,
                            shade: [0.2,'#000'], //0.1透明度的白色背景
                            time: false
                        });
                    },
                    success:function(data){
                        console.log(data)
                        layer.close(msg);
                        if (data.success) {
                            Feng.success("Submission successful!");
                            table.reload(OutOrder.tableId);
                        } else {
                            if (data.message !=null &&data.message!='') {
                                var msg2 =  layer.open({
                                    title: 'Notification' ,
                                    content: data.message,
                                    btn: ['Confirm'],
                                    yes: function (){
                                        layer.close(msg2);
                                        table.reload(OutOrder.tableId);
                                    }
                                });
                            } else {
                                Feng.error("Submission failed!");
                                table.reload(OutOrder.tableId);
                            }
                        }
                    },
                    error:function(data){
                        layer.close(msg);
                        Feng.error("Submission failed!" + data.responseJSON.message)
                        table.reload(OutOrder.tableId);
                    }
                })
            });
        } else {
            layer.alert('Please select at least one record');
        }
    };


    OutOrder.submitWhHshn = function () {
        var checkStatus = table.checkStatus('outOrderTable');
        data = checkStatus.data;
        if (data.length>0) {
            var ids = [];
            for (var i = 0; i < data.length; i++) {
                ids.push(data[i].id);
            }
            layer.confirm('Confirm selected orders for submission?', function(index){
                layer.close(index);
                var msg;
                $.ajax({
                    url:Feng.ctxPath + "/outOrder/submitsWhHshn?ids="+ids,
                    cache: false,
                    dataType:"json",
                    beforeSend:function(){
                        //弹出加载中
                        msg = layer.msg('Submitting... Please wait patiently', {
                            icon: 16,
                            shade: [0.2,'#000'], //0.1透明度的白色背景
                            time: false
                        });
                    },
                    success:function(data){
                        console.log(data)
                        layer.close(msg);
                        if (data.success) {
                            Feng.success("Submission successful!");
                            table.reload(OutOrder.tableId);
                        } else {
                            if (data.message !=null &&data.message!='') {
                                var msg2 =  layer.open({
                                    title: 'Notification' ,
                                    content: data.message,
                                    btn: ['Confirm'],
                                    yes: function (){
                                        layer.close(msg2);
                                        table.reload(OutOrder.tableId);
                                    }
                                });
                            } else {
                                Feng.error("Submission failed!");
                                table.reload(OutOrder.tableId);
                            }
                        }
                    },
                    error:function(data){
                        layer.close(msg);
                        Feng.error("Submission failed!" + data.responseJSON.message)
                        table.reload(OutOrder.tableId);
                    }
                })
            });
        } else {
            layer.alert('Please select at least one record');
        }
    };

    // 批量作废 Batch Cancellation
    OutOrder.cancel = function () {
        var checkStatus = table.checkStatus('outOrderTable');
        data = checkStatus.data;
        if (data.length>0) {
            var ids = [];
            for (var i = 0; i < data.length; i++) {
                ids.push(data[i].id);
            }
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/outOrder/cancel?ids="+ids, function (data) {
                    Feng.success("Cancellation successful!");
        			table.reload(OutOrder.tableId);
                }, function (data) {
                    Feng.error("Cancellation failed!" + data.responseJSON.message + "!");
                });
                ajax.start();
            };
            Feng.confirm("Confirm cancellation of selected orders?", operation);
        } else {
            layer.alert('Please select at least one record');
        }
    };

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        OutOrder.search();
    });
    // 搜索按钮点击事件
    $('#btnJSTOutOrder').click(function () {
        // alert(1111)
        OutOrder.toJSTOutOrder();
    });

    // 添加按钮点击事件
    $('#btnAdd').click(function () {
        // alert(222)
        OutOrder.openAddDlg();
    });

    // Export Excel
    $('#btnExp').click(function () {
        OutOrder.exportExcel();
    });

    // Import Excel
    $('#btnExpimport').click(function () {
    	OutOrder.importExcel();
    });

    // Import Excel
    $('#btnExpimportDD').click(function () {
        OutOrder.importExcelDD();
    });
    // Import Excel
    $('#btnExpimport_ha').click(function () {
    	OutOrder.importExcel_ha();
    });

    // Batch Submit
    $('#btnSubmits').click(function () {
        OutOrder.submit();
    });

    // Batch Submit
    $('#hshnBtnSubmits').click(function () {

        OutOrder.submitHshn();
    });

    // 批量提交【武汉】 Batch Submit [Wuhan]
    $('#hshnWhBtnSubmits').click(function () {

        OutOrder.submitWhHshn();
    });
    
    // 批量作废 Batch Cancellation
    $('#btnCancel').click(function () {
        OutOrder.cancel();
    });

    // Toolbar click event
    table.on('tool(' + OutOrder.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            OutOrder.openEditDlg(data);
        }else if (obj.event === 'outOrderStatusSign' && data.outOrderStatus == 'Rejected'){
            var index = layer.open({
                title: 'Review Details:',
                type: 1,
                title: false, //不显示标题栏
                closeBtn: false,
                shade: 0.3,
                area: '300px;',
                content: "<div style='padding: 50px; word-wrap: break-word;word-break: break-all;overflow: hidden; background-color: #000000; color: #fff;line-height: 22px;  font-weight: 300;'>Reviewer: "+data.examineName+"<br><br>Review Time: "+data.examineTime+"<br><br>Comments:<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"+data.returnNote+"</div>",
                btn: ['Confirm'] ,
                btnAlign: 'c' ,//按钮居中
                yes: function(){
                    layer.close(index);
                }
            });
        }
    });

    /**
     * 初始化表格的列
     */
    OutOrderDetailed.initColumn = function () {
        return [[
            {field: 'id', hide: true, title: 'Primary Key'},
            {field: 'detailedFactory', title: 'Factory No.', hide: true},
            {field: 'detailedGoodsname', sort: true, title: 'Product Name', style:'background-color: #dbf1e1;font-weight: 600;',width: 200},
            {field: 'detailedGoodscode', sort: true, title: 'Product Code', style:'background-color: #dbf1e1;font-weight: 600;'},
            {field: 'goodsNo', title: 'Item No.', style:'background-color: #dbf1e1;font-weight: 600;', totalRowText: 'Total:'},
            {field: 'detailedNumber', sort: true, title: 'Quantity', totalRow: true, style:'background-color: #dbf1e1;font-weight: 600;'},
            {field: 'kcCount', title: 'Inventory', style:'background-color: #dbf1e1;font-weight: 600;',width: 140},
            {field: 'cckcCount', title: 'Storage Location Inventory', style:'background-color: #dbf1e1;font-weight: 600;',width: 140},
            {field: 'jhkcCount', title: 'Picking Location Inventory', style:'background-color: #dbf1e1;font-weight: 600;',width: 140},
            {field: 'djhCount', title: 'Reserved Inventory', style:'background-color: #dbf1e1;font-weight: 600;',width: 140},
            {field: 'detailedDate', sort: true, title: 'Production Date', style:'background-color: #dbf1e1;font-weight: 600;',width: 140},
            {field: 'detailedBatchnumber', sort: true, title: 'Batch No.', style:'background-color: #dbf1e1;font-weight: 600;',width: 140},
            {field: 'detailedPrice', title: 'Unit Price'},
            {field: 'detailedMoney', sort: true, title: 'Amount', totalRow: true},
            {field: 'detailedOutVolume', sort: true, title: 'Volume', totalRow: true},
            {field: 'detailedOutWeight', sort: true, title: 'Weight', totalRow: true},
            {field: 'detailedLargeclass', title: 'Category'},
            {field: 'detailedGoodstype', title: 'Type', hide: true},
            {field: 'goodsUnit', title: 'Unit'},
            {field: 'detailedPacking', title: 'Packing'},
            {field: 'goodsSpecs', title: 'Specifications'},
            {align: 'center', toolbar: '#tableBarDetailed', title: 'Operations',fixed: 'right',width: 200}
        ]];
    };


    // Row click event
    table.on('row(' + OutOrder.tableId + ')', function (obj) {
        var data = obj.data;
		$('div[lay-id="' + OutOrder.tableId + '"]').find(".layui-table-body tr ").attr({ "style": "background:#FFFFFF" });//其他tr恢复原样
		$('div[lay-id="' + OutOrder.tableId + '"]').find(obj.tr.selector).attr({ "style": "background:#e6e6e6" });//改变当前tr颜色
        outOrder(data);
    });

    function outOrder(data){
        var outOrderNumber;
        if (data!=null) {
            $("#detailedOutNumber").val(data.outOrderNumber);
            outOrderNumber = data.outOrderNumber;
        } else {
            outOrderNumber = 'nodata';
        }
        // Render product details table 渲染商品明细表格
        var tableResult = table.render({
            elem: '#' + OutOrderDetailed.tableId,
            url: Feng.ctxPath + '/outOrderDetailed/list?detailedOutNumber=' + outOrderNumber,
            page: true,
            limit: 30,
            height: 400,
            toolbar: '#toolbarfromDetailed',
            cellMinWidth: 100,
            totalRow: true ,//开启合计行
            cols: OutOrderDetailed.initColumn()
        });

        /**
          * Click search button 点击查询按钮
          */
    	OutOrderDetailed.search = function () {
            var queryData = {};
            queryData['condition'] = $("#condition2").val();
            table.reload(OutOrderDetailed.tableId, {
                where: queryData, page: {curr: 1},
                 done:function () {
                     // Search button click event 搜索按钮点击事件
                     $('#btnSearchDetailed').click(function () {
                    	 OutOrderDetailed.search();
                     });
                     // Add button click event 添加按钮点击事件
                     $('#btnAddDetailed').click(function () {
                    	 OutOrderDetailed.addDetailed();
                     });
                }
            });
        };

    	OutOrderDetailed.addDetailed = function () {
            layer.open({
                type: 2,
                title: 'Add Order Details',
                area: ['1000px', '750px'],
                anim: 5,
                content: Feng.ctxPath + '/outOrderDetailed/add?detailedOutNumber=' + data.outOrderNumber+"&outCustomerId="+data.outCustomerId,
                end: function () {
                    outOrder(data);
                }
            });
        };

        // Toolbar click event 工具条点击事件
        table.on('tool(' + OutOrderDetailed.tableId + ')', function (obj) {
            var data2 = obj.data;
            var layEvent = obj.event;

            if (layEvent === 'editDetailed') {
                OutOrderDetailed.openEditDlg(data2);
            } else if (layEvent === 'deleteDetailed') {
                OutOrderDetailed.onDeleteItem(data2);
            } else if (layEvent === 'moveDetailed') {
                OutOrderDetailed.openMoveDlg(data2);
            }
        });

        // 修改按钮点击事件 Edit Button Click Event
        OutOrderDetailed.openEditDlg = function (data2) {
            layer.open({
                type: 2,
                title: 'Edit Order Details',
                area: ['1000px', '750px'],
                anim: 5,
                content: Feng.ctxPath + '/outOrderDetailed/edit?id='+data2.id+"&detailedOutNumber="+data.outOrderNumber+"&outCustomerId="+data.outCustomerId,
                end: function () {
                    outOrder(data);
                }
            });
        };

        // 修改按钮点击事件 Edit Button Click Event
        OutOrderDetailed.openMoveDlg = function (data2) {
            layer.open({
                type: 2,
                title: 'Move Details to Other Order',
                area: ['500px', '950px'],
                anim: 5,
                content: Feng.ctxPath + '/outOrderDetailed/moveOpen?id='+data2.id,
                end: function () {
                    OutOrderDetailed.search();
                }
            });
        };

        // 删除按钮点击事件 Delete Button Click Event
        OutOrderDetailed.onDeleteItem = function (data2) {
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/outOrderDetailed/delete", function (data2) {
                    Feng.success("Deletion successful!");
                    outOrder(data);
                }, function (data) {
                    Feng.error("Deletion failed!" + data2.responseJSON.message + "!");
                });
                ajax.set("id", data2.id);
                ajax.start();
            };
            Feng.confirm("Confirm deletion?", operation);
        };

        // Search button click event
        $('#btnSearchDetailed').click(function () {
        	OutOrderDetailed.search();
        });

        $('#btnAddDetailed').click(function () {
        	OutOrderDetailed.addDetailed();
        });

    }

});
